<template>
  <a-drawer
    :title="title"
    placement="right"
    :closable="true"
    :width="width"
    :visible="visible"
    @close="handleCancel"
    destroyOnClose
  >
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item label="供应商">
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择供应商"
                option-filter-prop="children"
                v-model="queryParam.supplierId"
                style="width: 100%"
                :filter-option="filterOptionSupplier"
                @change="changeSupplier">
                <a-select-option :value="item.id" v-for="(item,index) in supplierData" :key="index">
                  {{item.supplierName}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="下单状态">
              <a-select style="width: 100%" v-model="queryParam.placeOrderStatus" @change="changePlaceOrderStatus">
                <a-select-option value="0">
                  全部
                </a-select-option>
                <a-select-option value="1">
                  未下单
                </a-select-option>
                <a-select-option value="2">
                  已下单
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="搜索条件">
              <a-input-group compact>
                <a-select default-value="1" style="width: 30%" @change="changeConditionType">
                  <a-select-option value="1">
                    名称
                  </a-select-option>
                  <a-select-option value="2">
                    型号
                  </a-select-option>
                  <a-select-option value="3">
                    规格
                  </a-select-option>
                  <a-select-option value="4">
                    品牌
                  </a-select-option>
                </a-select>
                <a-input placeholder="请输入搜索内容" style="width: 70%" v-model="conditionValue"></a-input>
              </a-input-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-bottom: 10px">
          <a-col :span="12">
            <a-button type="primary" style="width: 100%" @click="searchQuery" icon="search">查询</a-button>
          </a-col>
          <a-col :span="12">
            <a-button type="primary" @click="searchReset" icon="reload" style="width: 100%">重置</a-button>
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-bottom: 10px">
          <a-col :span="24">
            <a-button type="primary" style="width: 100%" @click="handleOk" >下单</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div>
      <div class="list">
        <van-list
          v-model="loading"
          :finished="finished"
          offset="100"
          finished-text="没有更多了"
          @load="onLoadList"
          :immediate-check="false"
        >
          <div
            class="customer-list"
            v-for="(item,i) in dataSource"
            :key="i"
          >
            <div>
              <div class="name">材料名称：{{ item.materialName || '无' }}</div>
              <div class="contact">
                <span>供应商：{{ item.supplierName || '无' }}</span>
              </div>
              <div class="contact">
                <span>型号：{{ item.modelNumber || '无' }}</span>
                <span style="margin-left: 20px;">规格：{{ item.specifications||'无' }}</span>
              </div>
              <div class="contact">
                <span>品牌：{{ item.brand || '无' }}</span>
                <span style="margin-left: 20px;">单位：{{ item.unit || '无' }}</span>
              </div>
              <!--supplierName-->
              <div class="contact">
                <span>预算数量：{{ item.quantity }}</span>
                <span style="margin-left: 20px;margin-right: 20px">已下单数量：{{ item.orderedQuantity }}</span>
                <span>待下单数量：{{ item.expectQuantity }}</span>
              </div>
              <div class="contact">
                <!--item.realityQuantity-->
                <span style="display: inline-block;height: 25px">实际下单数量：
                  <a-input
                    type="number"
                    style="background: white;width: 120px;height: 25px;display: inline-block;text-align: center"
                    :value="item.realityQuantity"
                    :id="'realityQuantity'+item.key"
                    @change="(e) => handleChangeIndex(e.target.value, item.key, 'realityQuantity')"
                  />
                </span>
                <span style="float:right;">
                  <a-checkbox @click="checkClick(item,$event)"></a-checkbox>
                </span>
              </div>
              <div class="contact">
                <span>单价：{{ item.unitPrice }}</span>
                <span style="margin-left: 20px;margin-right: 20px">小计：{{ item.costTypeSubtotal }}</span>
                <span style="margin-left: 20px;">下单状态：
                  <a-tag color="green" v-if="item.placeOrderStatus == 2">已下单</a-tag>
                  <a-tag color="orange" v-else>未下单</a-tag>
                </span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <!--<a-table
        ref="table"
        size="middle"
        :scroll="{y:550}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{
              selectedRowKeys: selectedRowKeys,
              onSelectAll:onSelectAll,
              onSelect:onSelect,
              onChange: onSelectChange,
              type:'checkbox'
            }"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="unitPrice" slot-scope="text, record, index">
                <span :id="'unitPrice'+record.key">
                  {{text}}
                </span>
        </template>
        <template v-for="col in ['realityQuantity']" :slot="col" slot-scope="text, record, index">
          <div>
            <a-input
              type="number"
              style="margin: -5px 0;background: white;width: 90px;text-align: center"
              :value="text"
              :id="col+record.key"
              @blur="changeMaterialSubtotal(record.key,col)"
              @change="(e) => handleChangeIndex(e.target.value, record.key, col)"
            />
          </div>
        </template>
        <template slot="costTypeSubtotal" slot-scope="text, record, index">
                <span :id="'costTypeSubtotal'+record.key">
                  {{text}}
                </span>
        </template>
      </a-table>-->
    </div>
    <place-order-modal ref="placeOrderModal" @ok="placeOrderOk"></place-order-modal>
  </a-drawer>

</template>

<script>
  import { filterObj } from '@/utils/util'
  import { getAction, postAction } from '@/api/manage'
  import placeOrderModal from './placeOrderModal'

  export default {
    name: "costMaterialList",
    components: {
      placeOrderModal,
    },
    data() {
      return {
        width: '100%',
        model: {},
        title: "",
        columns:[
          {
            title:'材料编号',
            align:"center",
            dataIndex: 'materialSerial'
          },
          {
            title:'名称',
            align:"center",
            dataIndex: 'materialName',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'型号',
            align:"center",
            dataIndex: 'modelNumber',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'specifications',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'品牌',
            align:"center",
            dataIndex: 'brand',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'unit',
            width: "5%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '5%',
                }
              }
            }
          },
          {
            title:'供应商',
            align:"center",
            dataIndex: 'supplierName',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'材料状态',
            align:"center",
            dataIndex: 'status',
            customRender:function (text) {
              return text == 1 ? <a-tag color="green">启用</a-tag> : <a-tag color="orange">禁用</a-tag>
            }
          },
          {
            title:'单价/元',
            align:"center",
            dataIndex: 'unitPrice',
            scopedSlots: {customRender: 'unitPrice'},
          },
          {
            title:'预算成本数量',
            align:"center",
            dataIndex: 'quantity',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              } else {
                return text
              }
            }
          },
          {
            title: '实际下单数量',
            dataIndex: 'realityQuantity',
            align: "center",
            scopedSlots: {customRender: 'realityQuantity'},
          },
          {
            title: '已下单数量',
            dataIndex: 'orderedQuantity',
            align: "center",
          },
          {
            title: '待下单数量',
            dataIndex: 'expectQuantity',
            align: "center",
          },
          {
            title:'成本预算小计/元',
            align:"center",
            dataIndex: 'costTypeSubtotal',
            scopedSlots: {customRender: 'costTypeSubtotal'},
          },
          {
            title:'下单状态',
            align:"center",
            dataIndex: 'placeOrderStatus',
            customRender:function (text) {
              return text == 2 ? <a-tag color="green">已下单</a-tag> : <a-tag color="orange">未下单</a-tag>
            }
          },
        ],
        visible: false,
        finished: false,
        // 查询条件
        queryParam: {},
        //数据集
        dataSource: [],
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
        supplierData:[],
        ipagination:{
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        url: {
          supplierList: "/ghSupplychainSupplier/allList",
          costMaterialList: "/ghProjectPlaceOrder/costMaterialList",
        },
        conditionType: 1,
        conditionValue: '',
        currentCustomerId: 0,
      }
    },
    created() {
      this.loadSupplierData();
    },
    methods: {
      searchQuery() {
        this.queryParam.conditionValue = this.conditionValue;
        this.loadData(1);
      },
      searchReset() {
        this.queryParam = {};
        this.conditionValue = "";
        this.loadData(1);
      },
      handleCancel() {
        this.visible = false;
        this.queryParam = {};
        this.conditionValue = "";
        this.onClearSelected();
      },
      onLoadList(e){
        this.ipagination.current++
        this.loadData(this.ipagination.current)
      },
      loadData(arg) {
        this.loading = true;
        if (arg === 1) {
          this.ipagination.current = 1;
          this.dataSource = []
          this.finished = false;
        }
        let params = this.getQueryParams();
        if (params.placeOrderStatus == null){
          params.placeOrderStatus = 0
        }
        params.conditionType = this.conditionType;
        getAction(this.url.costMaterialList, params).then((res) => {
          if (res.success) {
            this.dataSource = [...this.dataSource, ...res.result.records]
            for (let i=0;i<this.dataSource.length;i++){
              this.dataSource[i].key = i.toString();
            }
            if (res.result.total) {
              this.ipagination.total = res.result.total;
            } else {
              this.ipagination.total = 0;
            }
          } else {
            this.$message.warning(res.message)
          }
          if(res.result.records.length<10){
            this.finished = true;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectedRows = [];
      },

      onSelectAll(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows = this.selectedRows.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows.splice(delIndex, 1)
          })
        }
      },
      onSelect(record, selected) {
        if(selected) {
          this.selectedRows.push(record);
        } else {
          const delIndex = this.selectedRows.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows.splice(delIndex,1)
        }
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      handleOk() {
        if (this.selectedRows.length <= 0){
          this.$message.warning("请至少选择一种材料下单")
          return;
        }
        this.$refs.placeOrderModal.add(this.selectedRows,this.currentCustomerId)
      },
      show(customerId){
        this.currentCustomerId = customerId;
        this.visible = true;
        this.title = "成本制作材料列表";
        this.loadData(1);
      },
      filterOptionSupplier(input, option){
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      changeSupplier(){
        this.loadData(1);
      },
      loadSupplierData(){
        getAction(this.url.supplierList).then((res) => {
          if (res.success) {
            this.supplierData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      changeConditionType(value){
        this.conditionType = value;
      },
      getQueryParams() {
        var param = Object.assign({}, this.queryParam, this.isorter);
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        param.customerId = this.currentCustomerId;
        return filterObj(param);
      },
      handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        this.ipagination = pagination;
        this.loadData();
      },
      placeOrderOk(){
        this.searchReset()
        this.onClearSelected();
      },
      changePlaceOrderStatus(){
        this.loadData(1)
      },
      //计算小计
      changeMaterialSubtotal(key,col){
        let realityQuantity = document.getElementById('realityQuantity' + key)
        let unitPrice = document.getElementById('unitPrice' + key).innerText
        let costTypeSubtotal = document.getElementById('costTypeSubtotal' + key)
        let subtotal = parseFloat(realityQuantity.value * parseFloat(unitPrice)).toFixed(2)
        costTypeSubtotal.innerText = subtotal;
        const target = this.dataSource.find(item => key === item.key)
        if (target) {
          target['costTypeSubtotal'] = subtotal
        }
      },
      //表格确定回调
      handleChangeIndex(value, key, column) {
        const dataSource = [...this.dataSource]
        const target = dataSource[key]
        if (target) {
          target[column] = Math.abs(value)
          let subtotal = parseFloat(value * target['unitPrice']).toFixed(2)
          target['costTypeSubtotal'] = subtotal
          this.dataSource = dataSource
        }
      },
      checkClick(record,e){
        if (e.target.checked){
          this.selectedRows.push(record);
        }else {
          const delIndex = this.selectedRows.findIndex((val) => {
            return val.id === record.id;
          })
          this.selectedRows.splice(delIndex,1)
        }
      }
    }
  }
</script>

<style scoped>
  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 15px;
    padding-bottom: 15px;
  }

  .anty-row-operator button {
    margin: 0 5px
  }

  .ant-btn-danger {
    background-color: #ffffff
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }

  .list{
    overflow-y: scroll;
    height:100vh;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .customer-list {
    align-items: center;
    border-top: 1px solid #d9d9d9;
    /*height: 120px;*/
  }
  .name{
    margin-top: 10px;
    margin-bottom: 5px;
    font-size: 13px;
    color: #161616;
    line-height: normal;
  }
  .contact{
    font-size: 12px;
    color: #a39f9f;
    margin-bottom: 5px;
  }
</style>

